package com.yty.system.controller;


import com.yty.system.entity.AccountInfo;
import com.yty.system.entity.Tree;
import com.yty.system.entity.vo.R;
import com.yty.system.service.IAccountInfoService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 1111
 * @since 2022-06-12
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理API")
public class UserController {

    @Autowired
    private IAccountInfoService accountInfoService;

    @Autowired
    @Qualifier("taskExecutor1")
    private TaskExecutor taskExecutor;

    @GetMapping("tree")
    public R tree() {
        List<Tree> list = accountInfoService.tree();
        return R.ok(list);
    }

    @GetMapping("exportPDF")
    public R exportPDF(HttpServletRequest request, HttpServletResponse response) {
        return R.ok();
    }

    /**
     * 导出word模板--->doc
     * templateName：模板文件名称（包含后缀），如：公证调查报告模板.ftl
     * templatePath：模板文件路径，如：/templates/ftl
     *
     */
    public static void exportWord(Object data, HttpServletRequest request, HttpServletResponse response, String templateName) throws Exception{
        Configuration configuration = new Configuration(Configuration.getVersion()); // 创建一个Configuration对象
        configuration.setDefaultEncoding("utf-8");

        // 选择模板
        Template template = configuration.getTemplate(templateName); //加载模板
        // 导出文件名
        String fileName = System.currentTimeMillis() + ".doc";
        // 导出文件路径
        String path = request.getSession().getServletContext().getRealPath(File.separator) + fileName;
        // 创建文件
        File file = new File(path);
        Writer out = new FileWriter(file);
        // 填充数据
        template.process(data, out); //调用模板对象的process方法输出文件
        // 下载文件
        byte[] buffer = new byte[1024];
        response.addHeader("Content-Disposition","attachment;filename=" + new String(fileName.getBytes(), "ISO-8859-1"));
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        OutputStream os = response.getOutputStream();
        int i = bis.read(buffer);
        while (i != -1) {
            os.write(buffer, 0, i);
            i = bis.read(buffer);
        }
        // 关闭流
        os.close();
        bis.close();
        fis.close();
        out.close();
        file.delete();
    }



    @GetMapping("listAsync1")
    public R listAsync1(int a) {
        long start = System.currentTimeMillis();
        // 返回结果
        List<String> results = new ArrayList<>();
        // 数据
        List<Integer> datas = new ArrayList<Integer>();
        for (int i = 0; i < a; i++) {
            datas.add(i);
        }
        // 异步处理
        CompletableFuture[] cf = datas.stream().map(data -> CompletableFuture.supplyAsync(() -> {
            return getDataById(data);
        }, taskExecutor).thenApply(r -> r).whenComplete((d, e) -> results.add(d))).toArray(CompletableFuture[]::new);
        CompletableFuture.allOf(cf).join();
        long end = System.currentTimeMillis();
        String s = "总共耗时" + (end - start) + "毫秒";
        System.out.println(s);
        System.out.println("返回数据：" + results);
        return R.ok(s);
    }

    private static String getDataById(Integer id) {
        System.out.println("getDataById: "+ id + "---" + Thread.currentThread().getName());
        try {
            Thread.sleep(1000L);
            return id+"";
        }catch (Exception e) {
            e.printStackTrace();
        }
        return "99";
    }



    @GetMapping("listAsync")
    public R listAsync(int a) {
        long start = System.currentTimeMillis();
        CompletableFuture[] cf = new CompletableFuture[a];
        for (int i = 0; i < a; i++) {
            int finalI = i;
            cf[i] = CompletableFuture.runAsync(() -> {
                getA(finalI);
            }, taskExecutor);
        }
        // 是否执行完毕
        CompletableFuture.allOf(cf).join();
        long end = System.currentTimeMillis();
        String s = "总共耗时" + (end - start) + "毫秒";
        System.out.println(s);
        return R.ok(s);
    }

    private void getA(int i) {
        try {
            System.out.println("---------" + i);
            Thread.sleep(1000L);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @GetMapping("list")
    @ApiOperation(value = "查询列表接口",notes = "查询所有的用户信息")    // 接口名称和描述
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "userName",value = "用户名"),
                    @ApiImplicitParam(paramType = "query",name = "pageNo",value = "起始页",dataType = "int",example = "1",required = true),
                    @ApiImplicitParam(paramType = "query",name = "pageSize",value = "每页显示的条数",dataType = "int",example = "10",required = true)
            })
    @ApiResponses({
            @ApiResponse(code = 200,message = "返回data字段说明",response = R.class)
    })
    public R listUser(String userName,Integer pageNo,Integer pageSize){
        List<String> list = new ArrayList<String>();
        return R.ok(list);
    }

    @DeleteMapping("deleteUser")
    @ApiOperation(value = "删除用户信息",notes = "删除用户信息")    // 接口名称和描述
    public R deleteUser(){
        return R.ok();
    }

    @PutMapping("add")
    @ApiOperation(value = "添加用户信息",notes = "添加用户信息")    // 接口名称和描述
    public R add(@RequestBody AccountInfo accountInfo){
        return R.ok();
    }
}
